const getStrByUnderlineBefore = function(str, sign) {
  let signStr = sign && sign !== '' ? sign : '_'
  let strIndex = str.indexOf(signStr);
	let resultStr = str.substr(0, strIndex);
	return resultStr;
}
const getStrByUnderlineAfter = function(str, sign) {
  let signStr = sign && sign !== '' ? sign : '_'
  let strIndex = str.indexOf(signStr) + 1;
	let resultStr = str.substr(strIndex, str.length);
	return resultStr;
}
const formatDate = function(format, fDate) {
  var date = fDate;
  var o = {
    "M+": date.getMonth() + 1,
    "d+": date.getDate(),
    "h+": date.getHours(),
    "m+": date.getMinutes(),
    "s+": date.getSeconds(),
    "q+": Math.floor((date.getMonth() + 3) / 3),
    "S": date.getMilliseconds() };
  if (/(y+)/.test(format)) format = format.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(format)) format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
  }return format;
}
const getBeforeDate = function(n) {
  const d = new Date()
  let mon = d.getMonth() + 1
  const day = d.getDate()
  if (day <= n) {
    if (mon > 1) {
      mon = mon - 1
    } else {
      mon = 12
    }
  }
  d.setDate(d.getDate() - n)
  return d
}
const json2ArraySort = function(jsonObject,key,type) {
  let array = []
  for(let key in jsonObject) {
    array.push(key)
  }
  array.sort()
  let resArray = []
  if(type === 'up') {
    for(let i = 0;i < array.length; i++) {
      let item = jsonObject[array[i]]
      if(key && key !== '') {
        item[key] = array[i]
      }
      resArray.push(item)
    }
  }else {
    for(let i = array.length - 1;i >= 0; i--) {
      let item = jsonObject[array[i]]
      if(key && key !== '') {
        item[key] = array[i]
      }
      resArray.push(item)
    }
  }
  return resArray
}
const getWeekNumber = function(y, m, d) {
  var targetDay = new Date(y, m - 1, d);
  var year = targetDay.getFullYear();
  var month = targetDay.getMonth();
  var days = targetDay.getDate();
  //那一天是那一年中的第多少天
  for (var i = 1; i < m; i++) {
      days += getMonthDays(year, i);
  }
  //那一年第一天是星期几
  var yearFirstDay = new Date(year, 0, 1).getDay() - 1;
  //计算是第几周
  days += yearFirstDay;
  var week = Math.ceil(days / 7);
  return week;
}
const isLeapYear = function(year) {
  return (year % 400 == 0) || (year % 4 == 0 && year % 100 != 0);
}
const getMonthDays = function(year, month) {
  return [31, (isLeapYear(year) ? 29 : 28), 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1];
}
export default {
  getStrByUnderlineBefore,
  getStrByUnderlineAfter,
  formatDate,
  getBeforeDate,
  json2ArraySort,
  getWeekNumber,
  getMonthDays
}
